﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Xml;
using NUnit.Framework;
using Secure.Client;

namespace Secure.Tests.Client
{
    [TestFixture]
    public class XmlRoleProviderConfigurationFixture
    {
        [Test]
        public void should_load_roles_from_a_config_file()
        {
            RoleProvider provider = new SimpleRoleProvider();
            XmlRoleProviderConfigurator.Configure(provider);

            string[] rolesForDavid = provider.GetRolesForUser("david");
            string[] rolesForDerrick = provider.GetRolesForUser("derrick");
            string[] rolesForMary = provider.GetRolesForUser("mary");

            Assert.AreEqual(new[] {"user", "admin"}, rolesForDavid);
            Assert.AreEqual(new[] {"user"}, rolesForDerrick);
            Assert.AreEqual(new[] {"user"}, rolesForMary);
        }
    }
}

namespace Secure.Client
{
    public static class XmlRoleProviderConfigurator
    {
        public static bool Configure()
        {
            return Configure(Roles.Provider);
        }

        public static bool Configure(RoleProvider provider)
        {
            XmlNode rootNode = (XmlNode)ConfigurationManager.GetSection("roles");

            foreach (XmlNode roleNode in rootNode.ChildNodes)
            {
                string roleName = roleNode.Attributes["name"].Value;

                provider.CreateRole(roleName);

                List<string> users = new List<string>();

                foreach (XmlNode userNode in roleNode.ChildNodes)
                {
                    if (userNode.Name == "user" && userNode.Attributes["login"] != null)
                    {
                        users.Add(userNode.Attributes["login"].Value);
                    }
                }

                provider.AddUsersToRoles(users.ToArray(), new [] {roleName});
            }

            return true;
        }
    }

    public class XmlRoleConfigurationSectionHandler : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            return section;
        }
    }

}
